package com.duoduo.gateway.config;

import lombok.RequiredArgsConstructor;
import org.springdoc.core.properties.AbstractSwaggerUiConfigProperties;
import org.springdoc.core.properties.SwaggerUiConfigProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Configuration;

import jakarta.annotation.PostConstruct;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @author lengleng
 * @date 2022/3/26
 * <p>
 * swagger 3.0 展示
 */
@RequiredArgsConstructor
@Configuration
public class SpringDocConfiguration {

	private final SwaggerUiConfigProperties swaggerUiConfigProperties;
	
	protected final RouteDefinitionLocator routeDefinitionLocator;

	// TODO 从配置文件读取或者从gateway路由中读取
	@PostConstruct
	public void afterPropertiesSet() {
		 List<RouteDefinition> definitions = routeDefinitionLocator.getRouteDefinitions().collectList().block();
	        definitions.stream().forEach(routeDefinition -> {
	        	if(routeDefinition.getId().endsWith("openapi")) {
	        		return;
	        	}
	            AbstractSwaggerUiConfigProperties.SwaggerUrl swaggerUrl = new AbstractSwaggerUiConfigProperties.SwaggerUrl(
	                    routeDefinition.getId().replace("ReactiveCompositeDiscoveryClient_", "").toLowerCase(),
	                    routeDefinition.getUri().toString().replace("lb://duo-", "").toLowerCase() + "/v3/api-docs", routeDefinition.getId()
	            );
	            Set<AbstractSwaggerUiConfigProperties.SwaggerUrl> urls = swaggerUiConfigProperties.getUrls();
	            if (urls == null) {
	                urls = new LinkedHashSet<>();
	                swaggerUiConfigProperties.setUrls(urls);
	            }
	            urls.add(swaggerUrl);
	        });

	}

}
